package com.xysd.express.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.xysd.express.R;
import com.xysd.express.activity.OrderDetailsActivity;
import com.xysd.express.adapter.OrderAdapter;
import com.xysd.express.base.BaseFragment;
import com.xysd.express.bean.OrderObj;
import com.xysd.express.bean.User;
import com.xysd.express.util.JSONParser;
import com.xysd.express.util.ToastUtil;
import com.xysd.express.util.http.HttpCallBack;
import com.xysd.express.util.http.HttpUtil;
import com.xysd.express.widget.BaseSwipeRefreshLayout;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
@ContentView(R.layout.fragment_order)
public class OrderFragment extends BaseFragment {
    @ViewInject(R.id.tab_layout)
    private TabLayout tabLayout;
    @ViewInject(R.id.order_rv)
    private RecyclerView order_rv;
    @ViewInject(R.id.swiperefreshlayout)
    private BaseSwipeRefreshLayout swiperefreshlayout;
    int page=1;
    int pageSize=10;
    int totleSize;
    int orderStatus;//订单状态
    List<OrderObj.Order>dataList;
    List<OrderObj.Order>allDataList=new ArrayList<>();
    OrderAdapter adapter;

    boolean isFirst=true;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return x.view().inject(this,inflater,container);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initTab();
        initRefresh();
        initRv();
    }

    private void initRv() {
        dataList=new ArrayList<>();
        adapter=new OrderAdapter(R.layout.item_order,mActivity);
        order_rv.setLayoutManager(new LinearLayoutManager(mActivity));
        order_rv.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent=new Intent(mActivity, OrderDetailsActivity.class);
                intent.putExtra("id",allDataList.get(position).OrderId);
                startActivity(intent);
            }
        });
    }

    private void initRefresh() {
        setSwipeRefreshLayout(swiperefreshlayout);
        setOnRefreshListener(new BaseSwipeRefreshLayout.OnRefresh() {
            @Override
            public void refresh() {
                page=1;
                allDataList.clear();
                getData();
            }
        });
    }


    //重写fragment是否对用户可视，当可视时加载数据（解决viewpager的预加载问题）
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isCanLoadData();
    }

    private void isCanLoadData() {
        if (getUserVisibleHint()) {
            if (User.getInstance().isLogin)
                getData();
        }
    }

    private void getData() {
        HttpUtil.getOrderList(page, pageSize, orderStatus, new HttpCallBack() {
            @Override
            public void onSuccess(String result) {
                Log.i("订单列表",result);
                String code= JSONParser.getStringFromJsonString("Status",result);
                String msg= JSONParser.getStringFromJsonString("Msg",result);
                if ("0".equals(code)){
                    isFirst=false;
                    dataList=new Gson().fromJson(result,OrderObj.class).Data;
                    totleSize=new Gson().fromJson(result,OrderObj.class).Total;

                    if(null==dataList||dataList.size()==0){
                        if (page==1){
                            adapter.setNewData(dataList);
                            allDataList=dataList;
                        }
                        adapter.loadMoreEnd();
                        return;
                    }
                    if (page==1){
                        adapter.setNewData(dataList);
                        allDataList=dataList;
                    }else {
                        adapter.addData(dataList);
                        allDataList.addAll(dataList);//加载下一页数据之后添加到总数据里面，以供adapter的onItemClickListener使用
                    }
                    //判断是否已经获取完所有数据
                    if (dataList.size()<pageSize){
                        adapter.loadMoreEnd();
                    }else {
                        if (page*pageSize==totleSize){
                            adapter.loadMoreEnd();
                        }else {
                            adapter.loadMoreComplete();
                        }
                    }
                }else {
                    ToastUtil.show(msg);
                }
            }

            @Override
            public void onFailure(String error) {
                Log.i("订单列表",error);
            }
        });
    }

    private void initTab() {
        tabLayout.addTab(tabLayout.newTab().setText("全部"));
        tabLayout.addTab(tabLayout.newTab().setText("待付款"));
        tabLayout.addTab(tabLayout.newTab().setText("待服务"));
        tabLayout.addTab(tabLayout.newTab().setText("服务中"));
        tabLayout.addTab(tabLayout.newTab().setText("已完成"));
        tabLayout.addTab(tabLayout.newTab().setText("已取消"));
        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                page=1;
                if ("全部".equals(tab.getText())){
                    orderStatus=0;
                    if (!isFirst)
                    getData();
                }
                if ("待付款".equals(tab.getText())){
                    orderStatus=1;
                    getData();
                }
                if ("待服务".equals(tab.getText())){
                    orderStatus=2;
                    getData();
                }
                if ("服务中".equals(tab.getText())){
                    orderStatus=3;
                    getData();
                }
                if ("已完成".equals(tab.getText())){
                    orderStatus=4;
                    getData();
                }
                if ("已取消".equals(tab.getText())){
                    orderStatus=5;
                    getData();
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }
}
